/*
Spotter Exercise Manager
Copyright 2011 Evan Nelson.

This file is part of Spotter Exercise Manager.

Spotter Exercise Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Spotter Exercise Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Spotter Exercise Manager.  If not, see <http://www.gnu.org/licenses/>.

The author can be contacted by emailing ean5533@gmail.com
*/

#include "editexercises.h"
#include "ui_editexercises.h"

#include <QSqlQuery>
#include <QPushButton>
#include <QMessageBox>
#include <QInputDialog>

#include "database.h"
#include "settings.h"

EditExercises::EditExercises(int mode, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditExercises)
{
    ui->setupUi(this);

    this->mode = mode;

    //set up column header resizing (can't be done in designer version 2.1)
    ui->tableExercises->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
    ui->tableExercises->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);

    //turn off irritating auto-close function of dialog
    ui->btnDone->setAutoDefault(false);
    connect(ui->btnDone, SIGNAL(clicked()), this, SLOT(accept()));

    ui->lblExists->setVisible(false);

    refreshTable();
}

void EditExercises::refreshTable() {
    ui->tableExercises->clearContents();
    ui->tableExercises->setRowCount(0);
    ui->tableExercises->setSortingEnabled(false);
    this->exercises.clear();

    QString exType = (mode == MODE_WT ? "Weightlifting" : "Endurance");
    QSqlQuery *query = Database::prepareQuery("SELECT e.exercise, count(w.weight) FROM Exercise e LEFT OUTER JOIN Weightlifting w ON e.exercise = w.exercise WHERE e.primaryType = '" + exType + "' GROUP BY e.exercise");
    query->exec();
    int curRow = 0;
    while(query->next()) {
        ui->tableExercises->setRowCount(curRow+1);
        ui->tableExercises->setItem(curRow, 0, new QTableWidgetItem(query->value(0).toString()));
        ui->tableExercises->setItem(curRow, 1, new QTableWidgetItem(query->value(1).toString()));

        this->exercises.append(query->value(0).toString());
        curRow++;
    }
    delete query;

    ui->tableExercises->setSortingEnabled(true);
    ui->tableExercises->sortByColumn(0, Qt::AscendingOrder);
}

EditExercises::~EditExercises()
{
    delete ui;
}

void EditExercises::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void EditExercises::on_btnAddExercise_clicked()
{
    if(ui->txtNewEx->text().isEmpty()) return;

    insertNewExercise(ui->txtNewEx->text(), this->mode);
    ui->txtNewEx->clear();
    refreshTable();
}

void EditExercises::on_txtNewEx_textEdited(QString text)
{
    if(exercises.contains(text, Qt::CaseInsensitive)) {
        ui->btnAddExercise->setEnabled(false);
        ui->lblExists->setVisible(true);
    } else {
        ui->btnAddExercise->setEnabled(true);
        ui->lblExists->setVisible(false);
    }
}

void EditExercises::on_txtNewEx_returnPressed()
{
    insertNewExercise(ui->txtNewEx->text(), this->mode);
    ui->txtNewEx->clear();
    refreshTable();
}

void EditExercises::insertNewExercise(QString ex, int mode) {
    QSqlQuery *query = Database::prepareQuery("INSERT INTO Exercise(exercise, primaryType) VALUES('"
                                                            + ex + "', "
                                                            + (mode == MODE_WT ? "'Weightlifting'" : "'Endurance'") + ")");
    query->exec();
    delete query;
}

void EditExercises::on_btnDeleteExercise_clicked()
{
    int curRow = ui->tableExercises->currentRow();
    QString curEx = ui->tableExercises->item(curRow, 0)->text();
    QString curExCount = ui->tableExercises->item(curRow, 1)->text();
    int resp = QMessageBox("Delete this exercise?", "Are you sure you want to delete the exercise '" + curEx + "'? All records with this exercise will be deleted! (It's recommended that you use \"Rename\" instead)",
                           QMessageBox::Question, QMessageBox::Ok, QMessageBox::Cancel, QMessageBox::NoButton, this).exec();

    if(resp == QMessageBox::Cancel) return;

    deleteExercise(curEx);

    this->refreshTable();
}

void EditExercises::deleteExercise(QString ex) {
    QSqlQuery *query = Database::prepareQuery("DELETE FROM Weightlifting WHERE exercise = '" + ex + "'");
    query->exec();
    delete query;

    query = Database::prepareQuery("DELETE FROM Exercise WHERE exercise = '" + ex + "'");
    query->exec();
    delete query;
}

void EditExercises::on_btnRenameExercise_clicked()
{
    QString exerciseToRename = ui->tableExercises->item(ui->tableExercises->currentRow(), 0)->text();

    bool ok;
    QString newName = QInputDialog::getText(this, "Ranaming an exercise", "Please type a new name for the exercise '" + exerciseToRename + "'", QLineEdit::Normal, "", &ok).trimmed();

    if(!ok || newName.isEmpty()) return;

    QSqlQuery *query = Database::prepareQuery("UPDATE exercise SET exercise = '" + newName + "' WHERE exercise = '" + exerciseToRename + "'");
    query->exec();
    delete query;

    QString exTable = (mode == MODE_WT ? "weightlifting" : "endurance");
    query = Database::prepareQuery("UPDATE " + exTable + " SET exercise = '" + newName + "' WHERE exercise = '" + exerciseToRename + "'");
    query->exec();
    delete query;

    refreshTable();
}
